package community.application.service;

import community.domain.model.Post;
import community.domain.repository.PostRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import user.domain.repository.UserRepository;
import user.domain.model.User;

import java.util.List;
//import java.util.Optional;

@Service
@RequiredArgsConstructor
public class PostService {

    private final PostRepository postRepository;
    private final UserRepository userRepository;

    public Post createPost(Post post) {
        if (post.getUserId() != null) {
            User user = userRepository.findById(post.getUserId()).orElse(null);
            post.setUser(user);
        }
        return postRepository.save(post);
    }

    public Post getPostById(Long id) {
        Post post = postRepository.findById(id).orElse(null);

        if (post != null && post.getUser() != null) {
            post.getUser().getUsername(); //  触发懒加载，确保 user 不为 null
        }

        return post;
    }


    public List<Post> getAllPosts() {
        return postRepository.findAll();
    }

    public Post updatePost(Post post) {
        return postRepository.save(post);
    }

    public void deletePost(Long id) {
        postRepository.deleteById(id);
    }

    // 添加这个方法
    public Long getCommentCount(Long postId) {
        return postRepository.getCommentCount(postId);
    }
}
